﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Net;
using System.Reflection;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using System.Windows.Navigation;
using CUWo.App.CustomControl;
using CUWo.Common;
using CUWo.Common.Entities;
using CUWo.Common.Entities.WoInterface.HttpJsonResult;
using CUWo.Common.WebHelper;
using CUWo.Common.WoInterfaceCommunication;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;

namespace CUWo.App.Views
{
    public partial class TrackDayTrend : PhoneApplicationPage
    {
        public TrackDayTrend()
        {
            InitializeComponent();


            this.BindHistoryTrackTrend();
        }

        /// <summary>
        /// 首页公告信息
        /// </summary>
        public void BindHistoryTrackTrend()
        {
            string mobileNumber = string.Empty;
            RomInfo romInfo = RomHelper.GetRomInfo();
            if (romInfo != null)
            {
                mobileNumber = romInfo.Mobile;
            }
            if (string.IsNullOrWhiteSpace(mobileNumber))
            {
                MessageToastManager.Show("未登录，请登录！", MessageToastLevel.Warn);
                return;
            }
            //获取请求地址
            string requestUrl = new CUWo.Common.WoInterfaceCommunication.TrackHistory().GetUrl(mobileNumber, DateTime.Now, DateTime.Now);
            LogHelper.LogInfo(requestUrl);
            //
            PopupProgressBar.OpenProgressBar();
            WebTaskHelper webTask = new WebTaskHelper(new Uri(requestUrl));
            IAsyncResult ia = webTask.BeginWebTask(delegate(IAsyncResult callBackResult)
            {
                try
                {
                    this.Dispatcher.BeginInvoke(() =>
                    {
                        #region 获取结果处理
                        string result = webTask.EndWebTask(callBackResult);
                        PopupProgressBar.CloseProgressBar();

                        if (string.IsNullOrWhiteSpace(result))
                        {
                            LogHelper.LogError("Result is empty.");
                            MessageToastManager.Show("未获取到数据！", MessageToastLevel.Error);
                            return;
                        }
                        //
                        if (result.StartsWith("exception:"))
                        {
                            LogHelper.LogError(result);
                            MessageToastManager.Show("网络连接失败！", MessageToastLevel.Error);
                            return;
                        }
                        LogHelper.LogInfo(result, this.GetType(), MethodBase.GetCurrentMethod());
                        //
                        JsonResultRootJsonCharacterString rootCharacterString = JSONHelper.Deserialize<JsonResultRootJsonCharacterString>(result);
                        if (rootCharacterString == null)
                        {
                            MessageToastManager.Show("返回结果为空！", MessageToastLevel.Error);
                        }
                        else
                        {
                            AESHelper aesHelper = new AESHelper(AESHelper.KeySize.Bits128, AESHelper.Hex2Byte(new CommunicationBase().CHANNEL_PASSWORD));
                            byte[] decryptByteResult = aesHelper.InvCipher(AESHelper.Hex2Byte(rootCharacterString.RootValue));
                            string decryptStringResult = Encoding.UTF8.GetString(decryptByteResult, 0, decryptByteResult.Length);
                            LogHelper.LogInfo("Decrypt:\t" + decryptStringResult);
                            JsonResultMessageTrackHistory jsonResult = JSONHelper.Deserialize<JsonResultMessageTrackHistory>(decryptStringResult);
                            if (jsonResult != null)
                            {
                                if (jsonResult.Msg != null)
                                {
                                    if (jsonResult.Msg.MessageErrors != null && jsonResult.Msg.MessageErrors.Count > 0)
                                    {
                                        MessageToastManager.Show(jsonResult.Msg.MessageErrors[0].MessageContent, MessageToastLevel.Error);
                                        //有错误
                                    }
                                    else if (jsonResult.Msg.MessageWarns != null && jsonResult.Msg.MessageWarns.Count > 0)
                                    {
                                        MessageToastManager.Show(jsonResult.Msg.MessageWarns[0].MessageContent, MessageToastLevel.Warn);
                                    }
                                    else
                                    {
                                        //成功
                                        if (jsonResult.Msg.MessagePrompts != null && jsonResult.Msg.MessagePrompts.Count > 0)
                                        {
                                            this.BindLstFlowInf(jsonResult.LstFlowInf);
                                        }
                                    }
                                }
                            }

                        }
                        #endregion 获取结果处理
                    });
                }
                catch (Exception err)
                {
                    PopupProgressBar.CloseProgressBar();
                    MessageToastManager.Show(err.Message);
                }
            }, webTask);
        }

        private void BindLstFlowInf(IList<LstFlowInf> lstFlowInfs)
        {
            if (!(lstFlowInfs != null && lstFlowInfs.Count > 0))
            {
                return;
            }

            var items = new ObservableCollection<LstFlowInf>(lstFlowInfs);
            if (!(items != null && items.Count > 0))
            {
                return;
            }
            //初始化
            var days = new Dictionary<string, double>();
            int currentDay = Convert.ToInt32(DateTime.Now.Day) - 1;
            do
            {
                days.Add(DateTime.Now.AddDays(-currentDay).ToString("yyyyMMdd"), 0d);
                currentDay--;
            } while (currentDay > 0);
            //赋值
            double maxValue = 0;
            foreach (LstFlowInf item in items)
            {
                if (item == null)
                    continue;
                if (days.ContainsKey(item.Dt))
                {
                    double value = 0d;
                    double.TryParse(item.Flw, out value);
                    days[item.Dt] = value;
                    if (value > maxValue)
                        maxValue = value;
                }
            }
            double barHeight = Application.Current.Host.Content.ActualHeight-240;
            double avgValue = barHeight / maxValue;
            //生成图
            foreach (var item in days)
            {
                if (item.Value <= 0)
                    continue;
                //图例
                //<Grid Background="Beige" VerticalAlignment="Bottom">
                //    <Grid.RowDefinitions>
                //        <RowDefinition></RowDefinition>
                //        <RowDefinition></RowDefinition>
                //    </Grid.RowDefinitions>
                //    <Border Grid.Row="1" Height="100" Width="12" Margin="0,0,30,0" Opacity="0.8" Background="#ff828282" BorderBrush="Blue" BorderThickness="1" VerticalAlignment="Bottom"></Border>
                //    <TextBlock Grid.Row="0" Text="100" Foreground="Black" FontSize="10"></TextBlock>
                //</Grid>
                Border borderFlowBar = new Border()
                {
                    Height = avgValue * item.Value,
                    Width = 12,
                    Margin = new Thickness(0, 0, 30, 0),
                    Background = new SolidColorBrush(Helper.HexToColor("#ff828282")),
                    BorderBrush = new SolidColorBrush(Helper.HexToColor("#ff1870d4")),
                    BorderThickness = new Thickness(1),
                    VerticalAlignment = VerticalAlignment.Bottom,
                    Opacity = 0.8
                };
                TextBlock txtbFlowValue = new TextBlock()
                {
                    Text = string.Concat(Math.Round(item.Value, 2).ToString(), "M"),
                    Foreground = new SolidColorBrush(Helper.HexToColor(Convert.ToString(Application.Current.Resources["DefaultForegroundColor"]))),
                    FontSize = 10,
                    HorizontalAlignment = HorizontalAlignment.Left
                };

                Grid grid = new Grid() { VerticalAlignment = VerticalAlignment.Bottom };
                grid.RowDefinitions.Add(new RowDefinition());
                grid.RowDefinitions.Add(new RowDefinition());
                Grid.SetRow(txtbFlowValue, 0);
                Grid.SetRow(borderFlowBar, 1);
                grid.Children.Add(borderFlowBar);
                grid.Children.Add(txtbFlowValue);
                //日期
                TextBlock txtBarDay = new TextBlock()
                {
                    FontSize = 16,
                    Text = item.Key.Substring(6, 2),
                    Width = 40,
                    Margin = new Thickness(0, 0, 2, 0),
                    FontStyle = FontStyles.Italic,
                    VerticalAlignment = VerticalAlignment.Top,
                    Foreground = new SolidColorBrush(Helper.HexToColor(Convert.ToString(Application.Current.Resources["DefaultForegroundColor"])))
                };
                this.panelBarColor.Children.Add(grid);
                this.panelBarDay.Children.Add(txtBarDay);
            }
        }

        private void pivot_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {

        }

    }
}